﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Marbles.Core.Content.Captcha;

namespace Marbles.Core.Handlers
{
    public class CaptchaHandler : HttpHandlerBase,IHttpHandlerBase
    {
        public string Verbs
        {
            get { return "*"; }
        }

        public bool Validate
        {
            get { return false; }
        }

        public string Path
        {
            get { return "Captcha.axd"; }
        }

        public string Name
        {
            get { return this.GetType().Name; }
        }

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(System.Web.HttpContext context)
        {
            string value = string.Empty;
            string cmd = "render";
            string key = Guid.NewGuid().ToString();
            int width = 200;
            int height = 50;
            int size = 6;
            if (context.Request.Params["w"] != null) { if (!Int32.TryParse(context.Request.Params["w"], out width)) { width = 200; } }
            if (context.Request.Params["h"] != null) { if (!Int32.TryParse(context.Request.Params["h"], out height)) { height = 100; } }
            if (context.Request.Params["s"] != null) { if (!Int32.TryParse(context.Request.Params["s"], out size)) { size = 6; } }
            if (context.Request.Params["cmd"] != null) { cmd = context.Request.Params["cmd"].ToLower(); }
            if (context.Request.Params["key"] != null) { key = context.Request.Params["key"].ToLower(); }
            if (context.Request.Params["value"] != null) { value = context.Request.Params["value"]; }

            switch (cmd)
            {
                case "render":
                    CaptchaImage img = new CaptchaImage(width, height, size);
                    context.Response.ContentType = img.ContentType;
                    img.Save(context.Response.OutputStream);
                    if (!string.IsNullOrEmpty(key))
                    {
                        context.Session.Add(key, img.Code);
                    }
                    break;
                case "validate":
                    context.Response.ContentType = "text/plain";
                    if (string.IsNullOrEmpty(key)) { context.Response.Write("false"); break; }
                    if (context.Session[key] == null) { context.Response.Write("false"); break; }
                    bool state = (context.Session[key].ToString() == value);

                    if (state)
                    {
                        context.Session.Remove(key);
                    }

                    context.Response.Write(state.ToString().ToLower());
                    break;
            }

            context.Response.Flush();
        }
    }
}